#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use GlobalConfig;
use Utils;


sub get_ts_status{
  my $tc_status=shift;
  my $ts_ind=shift;
  my ($passed,$failed,$timeout,$err)=(0) x 4;
  foreach my $chap(keys %$tc_status){
    if($chap =~  /$ts_ind,/){
        $passed++ if ($tc_status->{$chap} eq "passed");
        $failed++ if ($tc_status->{$chap} eq "failed");
        $timeout++ if ($tc_status->{$chap} eq "timeout");
    }
  }
  return($passed,$failed,$timeout,$err);
}

my $tc_status={};
my $ts_info={};
my $ts_tc_name={};
my $tc_number_in_ts={};
my ($total_tc_number_in_ts,$total_pass,$total_fail,$total_timeout,$total_error)=(0) x 5;
# my $tc_log={};

my $log_folder=$ARGV[0] || die "provide log folder!";

my $start_time=`basename $log_folder`;chomp($start_time);
open(F,"cat $log_folder/$config->{total_log}|") || die $!;
while(<F>){
#   my $chap;
  if(/$config->{log_tag_start_tc}:\s+\[((\d+),(\d+))\]\s+(\S+)::(\S+)/){
#     $chap=$1;
    my ($chap,$chap_ts,$chap_tc,$ts,$tc)=($1,$2,$3,$4,$5);
#     debug "$chap,$ts,$tc";
    $ts_tc_name->{$chap}=$tc;
    $ts_tc_name->{$chap_ts}=$ts;
#     $ts_info->{$chap_ts}=;
    $tc_number_in_ts->{$chap_ts}+=1;
    $total_tc_number_in_ts+=1;
#     $tc_log->{$chap} .= $_;
  }
  if(/$config->{log_tag_tc_status}:\s+\[(\S+)\]\s+(\S+)/){
    my ($chap,$tc_status_str)=($1,$2);
    #remove color definition.
    $tc_status_str=~s/\e\[\d+m//g;
#     debug $tc_status_str;
    $tc_status->{$chap}=$tc_status_str;
#     $tc_log->{$chap} .= $_;
  }
#   $tc_log->{$chap} .= $_;
}
close(F);

# print Data::Dumper->Dump([$tc_status],["tc_status"]);
# print Data::Dumper->Dump([$ts_tc_name],["ts_tc_name"]);
# print Data::Dumper->Dump([$tc_number_in_ts],["tc_number_in_ts"]);


my $R_TS_TC_TEXT="";

foreach my $i (1 .. scalar(keys %$tc_number_in_ts)){
  my ($passed,$failed,$timeout,$err)=get_ts_status($tc_status,$i);
  my ($ts_name,$ts_count)=($ts_tc_name->{$i},$tc_number_in_ts->{$i});
  my $ts_class="passClass";
  $ts_class="failClass" if ($failed ne 0);
  $ts_class="errorClass" if ($err ne 0 || $timeout ne 0 );
  $total_pass+=$passed; $total_fail+=$failed; $total_timeout+= $timeout;

#    print sprintf("%-30s %-10s %-10s %-10s %-10s %-10s\n",$ts_name,
#   $ts_count,$passed,$failed,$timeout,$err);
  
  my $R_TS_TEXT=<<EOF;
<tr class='$ts_class'>
    <td>$ts_name</td>
    <td>$ts_count</td>
    <td>$passed</td>
    <td>$failed</td>
    <td>$timeout</td>
    <td>$err</td>
    <td><a href="javascript:showClassDetail('c$i',$ts_count)">Detail</a></td>
</tr>

EOF
 
  $R_TS_TC_TEXT .= $R_TS_TEXT;
  
  foreach my $j(1 .. $ts_count){
    my($tc_name,$tc_status)=($ts_tc_name->{"$i,$j"},$tc_status->{"$i,$j"});
    my $tc_log=`cat $log_folder/${i}_${j}_TS__${ts_name}_TC__$tc_name.log | aha`;
    my $tc_class="none";
    my $tc_hiddenrow_class="hiddenRow";
    my $pt_ft="pt";
    if($tc_status eq "failed" || $tc_status eq "timeout" || $tc_status eq "error"){
      $tc_class = "failCase";
      $tc_hiddenrow_class="none";
      $pt_ft="ft";
    }
    
#     print "$tc_name,\n";
#     print "$tc_status,\n$tc_log\n";
  
    my $R_TC_TEXT=<<EOF;

<tr id='${pt_ft}$i.$j' class='$tc_hiddenrow_class'>
    <td class='$tc_class'><div class='testcase'>$tc_name</div></td>
    <td colspan='6' align='left'>

    <!--css div popup start-->
    <a class="popup_link" onfocus='this.blur();' href="javascript:showTestDetail('div_pt$i.$j')" >
        $tc_status</a>

    <div id='div_pt$i.$j' class="popup_window">
        <div style='text-align: right; color:red;cursor:pointer'>
        <a onfocus='this.blur();' onclick="document.getElementById('div_pt$i.$j').style.display = 'none' " >
           [x]</a>
        </div>
$tc_log
    </div>
    <!--css div popup end-->

    </td>
</tr>

EOF
    $R_TS_TC_TEXT .= $R_TC_TEXT;
  }
  $i++;
}

# print sprintf("%-30s %-10s %-10s %-10s %-10s %-10s\n","Total",$total_tc_number_in_ts,
#             $total_pass,$total_fail,$total_timeout,$total_error);

           
            
my $R_HEAD=<<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test Report</title>
    <meta name="generator" content="HTMLTestRunner 0.8.2"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

<style type="text/css" media="screen">
body        { font-family: verdana, arial, helvetica, sans-serif; font-size: 80%; }
table       { font-size: 100%; }
pre         { }

/* -- heading ---------------------------------------------------------------------- */
h1 {
        font-size: 16pt;
        color: gray;
}
.heading {
    margin-top: 0ex;
    margin-bottom: 1ex;
}

.heading .attribute {
    margin-top: 1ex;
    margin-bottom: 0;
}

.heading .description {
    margin-top: 4ex;
    margin-bottom: 6ex;
}

/* -- css div popup ------------------------------------------------------------------------ */
a.popup_link {
}

a.popup_link:hover {
    color: red;
}

.popup_window {
    display: none;
    position: relative;
    left: 0px;
    top: 0px;
    /*border: solid #627173 1px; */
    padding: 10px;
    /*background-color: #E6E6D6; */
    font-family: "Lucida Console", "Courier New", Courier, monospace;
    text-align: left;
    font-size: 8pt;
    width: 800px;
}

}
/* -- report ------------------------------------------------------------------------ */
#show_detail_line {
    margin-top: 3ex;
    margin-bottom: 1ex;
}
#result_table {
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #777;
}
#header_row {
    font-weight: bold;
    color: white;
    background-color: #777;
}
#result_table td {
    border: 1px solid #777;
    padding: 2px;
}
#total_row  { font-weight: bold; }
.passClass  { background-color: #6c6; }
.failClass  { background-color: #c60; }
.errorClass { background-color: #c00; }
.passCase   { color: #6c6; }
.failCase   { color: #c60; font-weight: bold; }
.errorCase  { color: #c00; font-weight: bold; }
.hiddenRow  { display: none; }
.testcase   { margin-left: 2em; }


/* -- ending ---------------------------------------------------------------------- */
#ending {
}

</style>

</head>
<body>
<script language="javascript" type="text/javascript"><!--
output_list = Array();

/* level - 0:Summary; 1:Failed; 2:All */
function showCase(level) {
    trs = document.getElementsByTagName("tr");
    for (var i = 0; i < trs.length; i++) {
        tr = trs[i];
        id = tr.id;
        if (id.substr(0,2) == 'ft') {
            if (level < 1) {
                tr.className = 'hiddenRow';
            }
            else {
                tr.className = '';
            }
        }
        if (id.substr(0,2) == 'pt') {
            if (level > 1) {
                tr.className = '';
            }
            else {
                tr.className = 'hiddenRow';
            }
        }
    }
}


function showClassDetail(cid, count) {
    var id_list = Array(count);
    var toHide = 1;
    for (var i = 0; i < count; i++) {
        tid0 = 't' + cid.substr(1) + '.' + (i+1);
        tid = 'f' + tid0;
        tr = document.getElementById(tid);
        if (!tr) {
            tid = 'p' + tid0;
            tr = document.getElementById(tid);
        }
        id_list[i] = tid;
        if (tr.className) {
            toHide = 0;
        }
    }
    for (var i = 0; i < count; i++) {
        tid = id_list[i];
        if (toHide) {
            document.getElementById('div_'+tid).style.display = 'none'
            document.getElementById(tid).className = 'hiddenRow';
        }
        else {
            document.getElementById(tid).className = '';
        }
    }
}


function showTestDetail(div_id){
    var details_div = document.getElementById(div_id)
    var displayState = details_div.style.display
    // alert(displayState)
    if (displayState != 'block' ) {
        displayState = 'block'
        details_div.style.display = 'block'
    }
    else {
        details_div.style.display = 'none'
    }
}


function html_escape(s) {
    s = s.replace(/&/g,'&amp;');
    s = s.replace(/</g,'&lt;');
    s = s.replace(/>/g,'&gt;');
    return s;
}

/* obsoleted by detail in <div>
function showOutput(id, name) {
    var w = window.open("", //url
                    name,
                    "resizable,scrollbars,status,width=800,height=450");
    d = w.document;
    d.write("<pre>");
    d.write(html_escape(output_list[id]));
    d.write("\n");
    d.write("<a href='javascript:window.close()'>close</a>\n");
    d.write("</pre>\n");
    d.close();
}
*/
--></script>

<div class='heading'>
<h1>Test Report</h1>
<p class='attribute'><strong>Start Time:</strong> $start_time</p>
<p class='attribute'><strong>Duration:</strong> <TODO> </p>
<p class='attribute'><strong>Status:</strong> Pass $total_pass Failure $total_fail Timeout $total_timeout Error $total_error</p>
<p class='attribute'><strong>Total Log:</strong> <a href="total_log.html" target="_blank">total log</a> </p>


<p class='description'></p>
</div>



<p id='show_detail_line'>Show
<a href='javascript:showCase(0)'>Summary</a>
<a href='javascript:showCase(1)'>Failed</a>
<a href='javascript:showCase(2)'>All</a>
</p>
<table id='result_table'>
<colgroup>
<col align='left' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
<col align='right' />
</colgroup>
<tr id='header_row'>
    <td>Test Suite/Test case</td>
    <td>Count</td>
    <td>Pass</td>
    <td>Fail</td>
    <td>timeout</td>
    <td>Error</td>
    <td>View</td>
</tr>

EOF

my $R_TS_TEXT=<<EOF;
<tr class='passClass'>
    <td>minds.cgibin.test.test_cgi.TestCGI</td>
    <td>6</td>
    <td>6</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td><a href="javascript:showClassDetail('c1',6)">Detail</a></td>
</tr>
EOF


            
my $R_TAIL=<<EOF;
<tr id='total_row'>
    <td>Total</td>
    <td>$total_tc_number_in_ts</td>
    <td>$total_pass</td>
    <td>$total_fail</td>
    <td>$total_timeout</td>    
    <td>$total_error</td>
    <td>&nbsp;</td>
</tr>
</table>

<div id='ending'>&nbsp;</div>

</body>
</html>

EOF
            


            
            
            
            
            
############################
#Start to write report file
############################



open(RPT,">report_out.html") || die $!;
print RPT "$R_HEAD\n";
print RPT "$R_TS_TC_TEXT\n";
print RPT "$R_TAIL\n";
close(RPT);
system("xdg-open report_out.html");

